package com.qw.qrweb.controller;

import com.alibaba.fastjson2.JSONObject;
import com.qw.qrweb.model.api.ApiResponse;
import com.qw.qrweb.model.dto.ContentDTO;
import com.qw.qrweb.model.dto.DayVisits;
import com.qw.qrweb.model.entity.LogEntity;
import com.qw.qrweb.service.ContentService;
import com.qw.qrweb.service.LogService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class ContentController {

    @Resource
    ContentService contentService;

    @Resource
    LogService logService;

    @PostMapping("/api/add-content")
    public String addContent(@RequestBody ContentDTO contentDTO) {
        contentService.addContent(contentDTO.getContent());
        return ApiResponse.ok("ok");
    }

    @GetMapping("/api/get-latest-content")
    public String getLastContent() {
        return ApiResponse.ok(contentService.getLastest());
    }

    @PostMapping("/api/upload/image")
    public ResponseEntity<String> uploadImage(@RequestParam("wangeditor-uploaded-image") MultipartFile image) {
        JSONObject responseJson = new JSONObject();
        try {
            // 这里添加保存文件的逻辑，假设保存后得到了一个可访问的文件URL
            String fileUrl = saveImage(image);

            // 构建返回的JSON数据
            JSONObject dataJson = new JSONObject();
            dataJson.put("url", fileUrl);
            dataJson.put("alt", "Image description"); // 可以是动态数据
            dataJson.put("href", "Image link"); // 可以是动态数据

            responseJson.put("errno", 0);
            responseJson.put("data", dataJson);
        } catch (Exception e) {
            // 发生错误时的逻辑
            responseJson.put("errno", 1);
            responseJson.put("message", "上传失败，原因：" + e.getMessage());
        }

        return ResponseEntity.ok(responseJson.toJSONString());
    }

    private String saveImage(MultipartFile image) throws IOException {
        // 处理图片保存逻辑
        String filePath;
        if (System.getProperty("os.name").startsWith("Windows")) {
            // Windows开发环境路径
            filePath = "C:\\data\\" + image.getOriginalFilename();
        } else {
            // 生产环境路径
            filePath = "/web/images/uploads/" + image.getOriginalFilename();
            //System.out.println("Original filename: " + image.getOriginalFilename());
            File destination = new File(filePath);
            image.transferTo(destination);
        }

            // 返回图片的访问URL
        return "http://8.140.241.122/qr/images/" + image.getOriginalFilename();
    }

    @GetMapping("/view-log")
    public String addViewLog(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        logService.addLog(ip);
        return ApiResponse.ok("ok");
    }

    @GetMapping("/logs/all")
    String getLogs() {
        return ApiResponse.ok(logService.getLogs());
    }

    @GetMapping("/logs/today")
    String getLogsToday() {
        return ApiResponse.ok(logService.getLogsToday());
    }

    @GetMapping("/logs/last-hour")
    String getLogsLastHour() {
        return ApiResponse.ok(logService.getLogsLastHour());
    }

    @GetMapping("/logs/last-week")
    String getVisitsLastWeek() {
        return ApiResponse.ok(logService.getVisitsLastWeek());
    }

    @GetMapping("/hourly-traffic")
    public ResponseEntity<?> getHourlyTrafficStats() {
        Map<String, Integer> stats = logService.getHourlyTrafficStats();
        // 将统计数据转换为前端所需的格式
        List<String> labels = new ArrayList<>(stats.keySet());
        List<Integer> counts = labels.stream().map(stats::get).collect(Collectors.toList());
        Map<String, Object> response = new HashMap<>();
        response.put("labels", labels);
        response.put("counts", counts);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/logs/last-5-minutes")
    String getVisitsLast5Minutes() {
        Map<String, Integer> map = new HashMap<>();
        map.put("count", logService.getLogsLast5Minutes().size());
        return ApiResponse.ok(map);
    }

    @GetMapping("/logs/last-10-minutes")
    String getVisitsLast10Minutes() {
        Map<String, Integer> map = new HashMap<>();
        map.put("count", logService.getLogsLast10Minutes().size());
        return ApiResponse.ok(map);
    }

    @GetMapping("/logs/last-30-minutes")
    String getVisitsLast30Minutes() {
        Map<String, Integer> map = new HashMap<>();
        map.put("count", logService.getLogsLast30Minutes().size());
        return ApiResponse.ok(map);
    }

    @GetMapping("/logs/visits-by-region")
    String getVisitsRegions() {
        return ApiResponse.ok(logService.getLogsRegions());
    }

    @GetMapping("/api/new-content-view")
    public String getNewContentViews() {
        int viewCount = logService.countNewContentViews();
        return ApiResponse.ok(viewCount);
    }

}
